//
//  ZLRefreshingControll.swift
//  新浪微博
//
//  Created by 朱玉龙 on 9/29/16.
//  Copyright © 2016 朱玉龙. All rights reserved.
//

import UIKit
enum RegreshStatus {
    case down
    case leave
    case refresh
}
let refreshHeight: CGFloat = 49

class ZLRefreshingControll: UIControl {
    
    var superView: UIScrollView?
    var reloadData: (() -> ())?
    var refreshStatus: RegreshStatus? {
        
        didSet {
            
            switch refreshStatus! {
            case .down:
                UIView.animate(withDuration: 0.5, animations: { 
                    
                    self.iconImageView.transform = CGAffineTransform.identity
                })
                iconImageView.isHidden = false
                titleLabel.text = "下拉刷新"
                self.isHidden = false
            case .leave:
                UIView.animate(withDuration: 0.5, animations: { 
                    
                    self.iconImageView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
              iconImageView.isHidden = false
                titleLabel.text = "松手刷新"
            case .refresh:
                iconImageView.isHidden = true
                self.activity.startAnimating()
                UIView.animate(withDuration: 1.5, animations: {
                    self.superView?.contentInset.top += refreshHeight
                    
                    }, completion: { (_) in
                        self.reloadData!()
                        UIView.animate(withDuration: 1, animations: { 
                            
                            self.superView?.contentInset.top = 64
                        })
                        self.isHidden = true
                })
            }
            print(self.superView?.contentOffset)
        }
        
    }
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -refreshHeight, width:screenWidth, height: refreshHeight))
        
        backgroundColor = UIColor.orange
      refreshStatus = .down
        setupUI()
    }
    
    
    
    
    //设置界面
    private func setupUI() {
        
        addSubview(titleLabel)
        addSubview(iconImageView)
        addSubview(activity)
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(self)
            make.leading.equalTo(self.snp.centerX).offset(5)
        }
        
        iconImageView.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(self)
            make.trailing.equalTo(self.snp.centerX).offset(-5)
        }
        
        activity.snp.makeConstraints { (make) in
            make.center.equalTo(iconImageView)
            make.height.width.equalTo(20)
        }
        
    }
    
    //MARK: 将要移动到父视图
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willRemoveSubview(newSuperview!)
        superView = newSuperview as? UIScrollView
        
        superView!.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let y = (self.superView?.contentOffset.y)!
        if self.refreshStatus == .down && y <= -refreshHeight - 64 {
            self.refreshStatus = .leave
            print("松手刷新")
        } else if self.refreshStatus == .leave && y > -refreshHeight - 64{
            self.refreshStatus = .down
            print("下拉刷新")
        }
        
        if self.refreshStatus == .leave && superView?.isDragging == false   {
            
            self.refreshStatus = .refresh
            print("正在刷新的的")
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var titleLabel: UILabel = UILabel(title: "下拉刷新", color: UIColor.darkGray, fontSize: 15)
    lazy var iconImageView: UIImageView = {
        
        let image = UIImage(named: "tableview_pull_refresh")
        let iv = UIImageView(image: image)
        return iv
    }()
    lazy var activity: UIActivityIndicatorView = {
        
        let av = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
        av.hidesWhenStopped = true
        return av
    }()
}
